package main

import (
	"fmt"
	"reflect"
	"sync"
	"time"
)

type Publisher struct {
	//listerMap map[reflect.Type][]Lister
	listerMap sync.Map
	once      sync.Once
}

func (p *Publisher) pub(event Event) {
}
func (p *Publisher) add(e Event, lister Lister) {
	typeOf := reflect.TypeOf(e)
	p.once.Do(func() {
		if _, ok := p.listerMap.Load(typeOf); !ok {
			p.listerMap.Store(typeOf, make([]Lister, 0, 1))
		}
	})

	load, _ := p.listerMap.Load(typeOf)
	listers := load.([]Lister)
	listers = append(listers, lister)
	p.listerMap.Store(typeOf, listers)
}

type Event interface {
	getName() string
}

type Lister func(Event)

type DemoEvent struct {
}

func (e *DemoEvent) getName() string {
	return "-------"
}

type DTA int

func (d *DTA) ddd(event Event) {
	fmt.Println("aa=======")
}

func main() {

	p1 := &Publisher{}
	var e *DemoEvent
	p1.add(e, func(event Event) {
		fmt.Println(event.getName())
	})
	d := DTA(9)
	p1.add(e, d.ddd)
	p1.pub(&DemoEvent{})

	p2 := &Publisher{}
	fmt.Println(reflect.TypeOf(p1) == reflect.TypeOf(p2))

	p3 := Publisher{}
	p4 := Publisher{}
	fmt.Println(reflect.TypeOf(p3) == reflect.TypeOf(p4))
	fmt.Println(reflect.TypeOf(p1) == reflect.TypeOf(p4))

	time.Sleep(5 * time.Second)
}
